import { Module } from 'vuex';
import { ILoginState } from './types';
import { IRootState } from '../types';
import {
  accountLoginRequest,
  getUserInfoRequest,
  getUserMenusRequest
} from '@/service/login/login';
import { IuserLogin } from '@/service/login/types';
import localCache from '@/utils/cache';
import { mapMenusToRoutes } from '@/utils/filterRoutes';
import { mapPermission } from '@/utils/mapPermission';
import router from '@/router';
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state: () => {
    return {
      token: localCache.getCache('token') || '',
      userInfo: localCache.getCache('userInfo') || {},
      menus: localCache.getCache('menus') || [],
      permission: []
    };
  },
  mutations: {
    saveToken(state, token: string) {
      state.token = token;
    },
    saveUserInfo(state, userInfo: object) {
      state.userInfo = userInfo;
    },
    saveUserMenus(state, menus: any[]) {
      state.menus = menus;
      const routes = mapMenusToRoutes(menus);
      //动态添加路由菜单
      routes.forEach((route) => {
        router.addRoute('main', route);
      });

      //mapPermission
      const permission = mapPermission(menus);
      state.permission = permission;
    }
  },
  actions: {
    async userLogin({ commit, dispatch }, palyload: IuserLogin) {
      const res = await accountLoginRequest(palyload);
      if (res.code === 1) {
        const { id, token } = res.data;
        commit('saveToken', token);
        localCache.setCache('token', token);
        localCache.setCache('id', id);
        dispatch('getUserInfo', id);
        // 获取初始化数据:部门、角色
        dispatch('getDepartmentList', null, { root: true });
      }
    },
    async getUserInfo({ commit, dispatch }, id: number) {
      const res = await getUserInfoRequest(id);
      if (res.code === 1) {
        commit('saveUserInfo', res.data);
        localCache.setCache('userInfo', res.data);
        dispatch('getUserMenus', res.data.role.id);
      }
    },
    async getUserMenus({ commit }, id) {
      const res = await getUserMenusRequest(id);
      // console.log(res);
      if (res.code === 1) {
        commit('saveUserMenus', res.data);
        localCache.setCache('menus', res.data);
        router.push('/main');
        return Promise.resolve(res.msg);
      } else {
        return new Error(res.msg);
      }
    },
    userLogOut() {
      localCache.clearCache();
      router.push('/');
    }
    //防止用户刷新页面时，state中的数据丢失
    // loadLocalLogin({ commit }) {
    //   const token = localCache.getCache('token');
    //   if (token) {
    //     commit('saveToken', token);
    //   }
    //   const userInfo = localCache.getCache('userInfo');
    //   if (userInfo) {
    //     commit('saveUserInfo', userInfo);
    //   }
    //   const menus = localCache.getCache('menus');
    //   if (menus) {
    //     commit(' ', menus);
    //   }
    // }
  }
};

export default loginModule;
